from telethon.sync import TelegramClient
import telethon.errors
from telethon.tl.types import PeerChannel
import ldap

api_id = 27287464
api_hash = "396195b11c37431d723b84f49497e979"
phone_number = '79271774335'
# ID группы, участников которой нужно получить

# Создание клиента7
client = TelegramClient('session_name', api_id, api_hash)
user_ids = []
group_link = "https://t.me/+VRVkHQqxCUM4N2Yy"


async def main():
    await client.start(phone_number)

    # Получение информации о группе
    group = await client.get_entity(group_link)
    # Получение участников
    async for participant in client.iter_participants(group):
        print(
            f"ID: {participant.id}, Username: {participant.username}, Name: {participant.first_name} {participant.last_name}")
        user_ids.append(participant.id)
    global lconn
    try:
        lconn = ldap.initialize('ldap://mos.renlife.com:389')
        lconn.protocol_version = ldap.VERSION3
        lconn.set_option(ldap.OPT_REFERRALS, 0)
        lconn.simple_bind_s('renlife\\balanil_adm', '$GyGy7j7IP')
    except ldap.SERVER_DOWN:
        print("Error connection to AD")
    for user_id in user_ids:
        print("-----------------------")
        print(user_id)
        base = 'dc=mos,dc=renlife,dc=com'
        scope = ldap.SCOPE_SUBTREE
        tgID = str(user_id)
        filter = '(&(extensionAttribute15=' + tgID + '))'
        attrs = ['extensionAttribute15']

        ldap_result_id = lconn.search_ext(base, scope, filter, attrs)
        result_set = []
        try:
            while 1:
                result_type, result_data = lconn.result(ldap_result_id, 0)
                if not result_data:
                    break
                else:
                    if result_type == ldap.RES_SEARCH_ENTRY:
                        result_set.append(result_data)
        except ldap.SIZELIMIT_EXCEEDED:
            print()
        print(result_set)
        if len(result_set) == 0:
            try:
                await client.kick_participant(group.id, user_id)

                print("Kicked")
            except:
                print("Error kicking user")





# Запуск асинхронной функции
with client:
    client.loop.run_until_complete(main())
